package com.powervision.http.base

import android.util.Log
import androidx.viewbinding.BuildConfig
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

abstract class BaseRetrofitClient {
    private val TAG = "OkHttp"

    companion object CLIENT {
        private const val TIME_OUT = 5
    }

    private val client: OkHttpClient by lazy {
        val builder = OkHttpClient.Builder()
                .addInterceptor(getHttpLoggingInterceptor())
                .addInterceptor(interceptor)
                .addInterceptor(headInterceptor)
                .connectTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
        handleBuilder(builder)
        builder.build()
    }

    private fun getHttpLoggingInterceptor(): HttpLoggingInterceptor {
        val logging = HttpLoggingInterceptor()
        if (BuildConfig.DEBUG) {
            logging.level = HttpLoggingInterceptor.Level.BODY
        } else {
            logging.level = HttpLoggingInterceptor.Level.BASIC
        }
        return logging
    }

    abstract fun handleBuilder(builder: OkHttpClient.Builder)

    open fun <Service> getService(serviceClass: Class<Service>, baseUrl: String): Service {
        return Retrofit.Builder()
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build()
                .create(serviceClass)
    }

    /**
     * 请求访问quest
     * response拦截器
     */
    private val interceptor = Interceptor { chain ->
        val request = chain.request()
        val startTime = System.currentTimeMillis()
        val response = chain.proceed(chain.request())
        val endTime = System.currentTimeMillis()
        val duration = endTime - startTime
        val mediaType = response.body?.contentType()
        val content = response.body?.string()
        Log.e(TAG, "----------Request Start----------------")
        Log.e(TAG, "| " + request.toString() + request.headers.toString())
        Log.e(TAG, "| Response:$content")
        Log.e(TAG, "----------Request End:" + duration + "毫秒----------")
        response.newBuilder()
            .body(content?.let { ResponseBody.create(mediaType, it) })
            .build()
    }
    private val headInterceptor = Interceptor { chain ->
        var request = chain.request()

        //获取到方法
        val method = request.method
        if (method == "GET") {
            val httpUrlurl = request.url
            val url = httpUrlurl.toString()
            val index = url.indexOf("?")
            if (index > 0) {
                //url = url + "&APP_KEY=" + AppConstant.APP_KEY;
            } else {
                //  url = url + "?APP_KEY=" + AppConstant.APP_KEY;  //拼接新的url
            }
            request = request.newBuilder().url(url).build() //重新构建请求
        } else if (method == "POST") {
            val requestBuilder = request.newBuilder()

            //请求体定制：统一添加token参数
            if (request.body?.contentLength() == 0L) {
                //没有参数
                val newFormBody = FormBody.Builder()
                //newFormBody.add("APP_KEY", AppConstant.APP_KEY);
                //newFormBody.add("APP_TOKEN", UserImpl.getAppToken());
                //newFormBody.add("version", AppUtils.getVersionName(App.getInstance()));
                requestBuilder.method(request.method, newFormBody.build())
            } else if (request.body is FormBody) {
                //正常post
                val newFormBody = FormBody.Builder()
                val oidFormBody = request.body as FormBody?
                for (i in 0 until oidFormBody!!.size) {
                    newFormBody.addEncoded(oidFormBody.encodedName(i), oidFormBody.encodedValue(i))
                }
                //newFormBody.add("APP_KEY", AppConstant.APP_KEY);
                // newFormBody.add("APP_TOKEN", UserImpl.getAppToken());
                // newFormBody.add("version", AppUtils.getVersionName(App.getInstance()));
                requestBuilder.method(request.method, newFormBody.build())
            }
            request = requestBuilder.build()
        }
        chain.proceed(request)
    }
}
